/**
 * @name:moko图片延迟加载
 * @example:
 * 	默认:
 * 		html:	<img src2 = "图片地址" />
 * 		code:	jQuery1(document).ready(function(){
 *	 				jQuery1.mk.imgLazyLoad();
 * 				});
 * 	自定义:
 * 		html:	<img picpath = "图片地址" />
 * 		code:	jQuery1(document).ready(function(){
 *	 				jQuery1.mk.imgLazyLoad({
 *						lazySrcName:"picpath"
 *					});
 * 				});	
 */
(function($) {
	if (typeof $.mk == "undefined") {
		$.mk = {};
	}
	
	$.mk.imgLazyLoad= function(options){
		// 构造最终参数(默认参数设置与自定义参数合并)
		var settings = $.extend({
			lazySrcName : "src2",//存储img src的自定义属性名称
			scrollStep: 200//滚动步长
		}, options),		
		imgLoadStatus = 0,
		$window = $(window),
		_lazyLoad = function(){
		    // 要懒加载的img数组。
		    var defObj = $("img["+settings.lazySrcName+"]");
		
			// 图片加载的范围
		    var pageTop = function () {
		        return $(window).height() + $(window).scrollTop();
		    };
		
		    _imgLoad(defObj, pageTop());
		    var scrollCount = 0;
		    // 绑定滚动事件。
		    $window.bind("scroll", function () {
		        // 往回移动就是负数
		        var moved = Math.abs($window.scrollTop() - scrollCount);
		        // 累计滚动达到一定的值再去加载图片
		        if (moved >= settings.scrollStep) {
		            _imgLoad(defObj, pageTop());
		            if (imgLoadStatus == 1) {
		                scrollCount += settings.scrollStep;
		                imgLoadStatus = 0;
		            }
		        }
		    });
		},
		_imgLoad = function(defObj, pageTop) {
			// 防止页面有新的图片元素
			defObj = $("img["+settings.lazySrcName+"]");
		    defObj.each(function () {
		        var src2 = $(this).attr(settings.lazySrcName);
		        if (src2) {
		            var imgTop = _getPosition($(this)[0]).y;
		            // 如果当前图片 的 top 值 在最大加载范围内。
		            if (imgTop <= pageTop
		            // 如果当前图片 的 底边 位置 值 大于 滚动条滚动的距离
		            && (imgTop + $(this).height()) >= $window.scrollTop()) {
		                // 将src2的值载入src，并且移除src2属性。
		                $(this).attr("src", src2).removeAttr(settings.lazySrcName);
		            }
		        }
		    });
		    imgLoadStatus = 1;
		},
		//获取元素坐标
		_getPosition = function(element) {
		    var ua = navigator.userAgent.toLowerCase();
		    var isOpera = (ua.indexOf('opera') != -1);
		    var isIE = (ua.indexOf('msie') != -1 && !isOpera); // not opera spoof
		    var el = element;
		    if (el.parentNode === null || el.style.display == 'none') {
		        return false;
		    }
		    var parent = null;
		    var pos = [];
		    var box;
		    if (el.getBoundingClientRect) { //IE
		        box = el.getBoundingClientRect();
		        if (ua.indexOf('ipad') != -1) { //ipad
		            return {
		                x: box.left,
		                y: box.top
		            };
		        }
		        var scrollTop = $(window).scrollTop();
		        var scrollLeft = $(window).scrollLeft();
		        return {
		            x: box.left + scrollLeft,
		            y: box.top + scrollTop
		        };
		    } else if (document.getBoxObjectFor) { // gecko    
		        box = document.getBoxObjectFor(el);
		        var borderLeft = (el.style.borderLeftWidth) ? parseInt(el.style.borderLeftWidth) : 0;
		        var borderTop = (el.style.borderTopWidth) ? parseInt(el.style.borderTopWidth) : 0;
		        pos = [box.x - borderLeft, box.y - borderTop];
		    } else { // safari & opera    
		        pos = [el.offsetLeft, el.offsetTop];
		        parent = el.offsetParent;
		        if (parent != el) {
		            while (parent) {
		                pos[0] += parent.offsetLeft;
		                pos[1] += parent.offsetTop;
		                parent = parent.offsetParent;
		            }
		        }
		        if (ua.indexOf('opera') != -1 || (ua.indexOf('safari') != -1 && el.style.position == 'absolute')) {
		            pos[0] -= document.body.offsetLeft;
		            pos[1] -= document.body.offsetTop;
		        }
		    }
		    if (el.parentNode) {
		        parent = el.parentNode;
		    } else {
		        parent = null;
		    }
		    while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML') { // account for any scrolled ancestors
		        pos[0] -= parent.scrollLeft;
		        pos[1] -= parent.scrollTop;
		        if (parent.parentNode) {
		            parent = parent.parentNode;
		        } else {
		            parent = null;
		        }
		    }
		    return {
		        x: pos[0],
		        y: pos[1]
		    };
		};
		_lazyLoad();
	}
})(jQuery1);
jQuery1(function(){
	jQuery1.mk.imgLazyLoad();
});